<?php
/*
	处理过期订单
	参考源文件：\Application\Auction\Controller\OrderController.class.php
*/
defined('BY_JYA') or exit('error');
$Orderset=plugin_set2('order');
$Orderset['losetime1']=$Orderset['losetime1']?$Orderset['losetime1']:1;
$losetime1 = TIMESTAMP + ($Orderset['losetime1']*60*60);
$list=pdo_getall('jy_weishop_order',array('plugin_name'=>'jy_jdpm','createtime <'=>$losetime1,'status'=>0),array('id','uniacid','mid','merchid','price','createtime'));
if(empty($list)){
	return true;
}
foreach($list as $k=>&$item){
	$order=pdo_get('jy_jdpm_order',array('orderid'=>$item['id']),array('margin','pid'));
	if(!$order['pid']){
		unset($list[$k]);
		continue;
	}
	$item=array_merge($order,$item);
	$item['onset']=pdo_getcolumn('jy_jdpm_auction',array('id'=>$item['pid']),'onset');
	pdo_update('jy_jdpm_auction',array('endstatus'=>2), array('id'=>$item['pid']));
	$user=pdo_get('jy_jdpm_member',array('mid'=>$item['mid']),array('wallet_pledge','wallet_pledge_freeze'));
	$item=array_merge($user,$item);
}
//file_put_contents(date('Y-m-d H:i:s') . ' 违约订单处理.txt' , json_encode($list));
$Log       = [];
$UpOrder   = [];
$UpUser    = [];
$GoodsUser = [];
//违约比例
$w_mid  = $Orderset['w_mid'] ? $Orderset['w_mid'] : 0.08;//违约保证金×8%
$w_merchid   = $Orderset['w_merchid'] ? $Orderset['w_merchid'] : 0.20;//违约保证金×20%
$w_agent      = $Orderset['w_agent'] ? $Orderset['w_agent'] : 0.02;//违约保证金×2%×有归属经纪人的用户有效竞拍次数/（总竞拍次数-1）；成交人除外，没有经纪人的收益算入平台中；首拍违约，无有效竞拍人，没有经纪人所得收益。
$w_jpuser     = $Orderset['w_jpuser'] ? $Orderset['w_jpuser'] : 0.30;//违约保证金×30%×该用户的有效竞拍次数/（总竞拍次数-1）成交人除外；首拍违约时，无竞拍人所得。
foreach ($list as $Order) {
	$_SESSION['uniacid']=$Order['uniacid'];
	//委托人所得保证金*20%
    $merchfee = round($Order['margin'] * $w_merchid,2);//委托人所得保证金*20%
	//拓展商所得违约保证金*8%
	$midfee = round($Order['margin'] * $w_mid,2);//拓展商所得违约保证金*8%
	//平台所得（总减）
	$systemfee   = $Order['margin'] - $merchfee - $midfee;
	
	$UserList=pdo_getall('jy_jdpm_freezelog',array('pid'=>$Order['pid'],'status'=>1),array('mid','createtime'));
	$num    = count($UserList);
	if ($UserList) {
		foreach($UserList as $k=>$userv){
			//如果竞拍人不存在，剔除
			$inuid = pdo_getcolumn('jy_jdpm_member', array('mid' => $userv['mid']),'mid');
			if(empty($inuid)){
				unset($UserList[$k]);
			}
		}
			//竞买人：违约保证金×30%
			$jpuserfee  = round($Order['margin'] * $w_jpuser/$num,2);
			//经纪人：违约保证金×2%
			$agentfee  = round($Order['margin'] * $w_agent/$num,2);
			//减出竞买人-平台所得
			$systemfee = $systemfee - ($jpuserfee*$num);
	}
	$UpOrder[] = [
            'id'         => $Order['id'] ,
            'status'     => 4 ,
    ];     //更新订单
	pdo_update('jy_jdpm_freezelog',array('status'=>3,'rtime'=>time()), array('pid'=>$Order['pid'],'mid'=>$Order['mid'],'status'=>0));
	
			//保证金解冻
			$Log[]=[
                        'mid'          => (int)$Order['mid'],
                        'money'        => $Order['margin'] ,
                        'channel'      => 1 ,
                        'create_time'  => time()-1 ,
                        'update_time'  => time()-1 ,
                        'auction_time' => 0 ,
                        'remarks'      => '违约解冻' ,
						'role'         => '违约者',
                        'type'         => 16 ,
						'uniacid'=>$_SESSION['uniacid']
                       
			];
            $Log[]      = [
                'mid'          => (int)$Order['mid'] ,
                'money'        => $Order['margin'] ,
                'channel'      => 2 ,
                'create_time'  => time() ,
                'update_time'  => time() ,
                'auction_time' => 0 ,
                'remarks'      => '过期订单未支付扣除' ,
                'type'         => 6 ,
                'pid'          => $Order['pid'] ,
                'role'         => '成交人',
				'uniacid'=>$_SESSION['uniacid']
            ];
			//送拍人
            $Log[]      = [
                'mid'          => (int)$Order['merchid'] ,
                'money'        => $merchfee ,
                'channel'      => 1 ,
                'create_time'  => time() ,
                'update_time'  => time() ,
                'auction_time' => 1 ,
                'remarks'      => '过期订单收取违约金' ,
                'type'         => 8 ,
                'pid'          => $Order['pid'] ,
                'role'         => '送拍人',
				'uniacid'=>$_SESSION['uniacid']
            ];
			//送拍商
			$Log[]      = [
                'mid'          => (int)$Order['mid'] ,
                'money'        => $midfee ,
                'channel'      => 1 ,
                'create_time'  => time() ,
                'update_time'  => time() ,
                'auction_time' => 1 ,
                'remarks'      => '过期订单收取违约金' ,
                'type'         => 8 ,
                'pid'          => $Order['pid'] ,
                'role'         => '送拍商',
				'uniacid'=>$_SESSION['uniacid']
            ];
			//违约人减冻结资金
            $UpUser[] = [
                'mid'                  => (int)$Order['mid'] ,
                'type'                 => '-' ,
                'wallet_pledge_freeze' => $Order['margin']
            ];
            $UpUser[] = [
                'mid'           => (int)$Order['mid'] ,
                'type'          => '-' ,
                'wallet_pledge' => $Order['margin']
            ];
			//送拍人加
            $UpUser[] = [
                'mid'           => (int)$Order['merchid'] ,
                'type'          => '+' ,
                'wallet_pledge' => $merchfee ,
            ];
			//送拍商加
			 $UpUser[] = [
                'mid'           => (int)$Order['mid'] ,
                'type'          => '+' ,
                'wallet_pledge' => $midfee ,
            ];
			//发放竞拍拥金
			$sharefee =0;
            if (!empty($UserList)) {
					foreach ($UserList AS $value) {
						pdo_update('jy_jdpm_member',array('brokerage +='=>$jpuserfee,'wallet_pledge +='=>$jpuserfee),array('mid'=>$value['mid']));
						$Log[] = [
							'mid'          => (int)$value['mid'] ,
							'money'        => $jpuserfee ,
							'channel'      => 1 ,
							'create_time'  => time() ,
							'update_time'  => time() ,
							'auction_time' => (int)$value['createtime'] ,
							'remarks'      => '竞拍次得到奖励' ,
							'type'         => 3 ,
							'pid'          => $Order['pid'],
							'uniacid'=>$_SESSION['uniacid']
						];
						$sourceuid=	pdo_getcolumn('core_members',array('id'=>$value['mid']),'fromuser');
						if($sourceuid){
							//推广分享金
							pdo_update('jy_jdpm_member',array('brokerage +='=>$agentfee,'wallet_pledge +='=>$agentfee),array('mid'=>$sourceuid));
							$Log[] = [
								'mid'          => $sourceuid ,
								'comuid'       => $value['mid'],
								'money'        => $agentfee ,
								'channel'      => 1 ,
								'create_time'  => time() ,
								'update_time'  => time() ,
								'auction_time' => 0 ,
								'remarks'      => '推广分享金收入' ,
								'role'         => '平台经纪人',
								'type'         => 7,
								'pid'          => $Order['pid'],
								'uniacid'=>$_SESSION['uniacid']
							];	
							$sharefee +=$agentfee;
						}
					}
            }
			$Log[]  = [
					'mid'          => 0 ,
					'money'        => $systemfee - $sharefee,
					'channel'      => 1 ,
					'create_time'  => time() ,
					'update_time'  => time() ,
					'auction_time' => 0 ,
					'remarks'      => '过期订单收取违约金' ,
					'type'         => 8 ,
					'pid'          => $Order['pid'] ,
					'role'         => '平台'
					'uniacid'=>$_SESSION['uniacid']
			];
			
			//推送信息：
			$message='竞拍失败！已违约过期支付，并扣除相应保证金！';
			set_websms2($message,'',$Order['mid'],'',$Order['pid']);
            $GoodsUser[] = $Order['pid'];//更新保证金表
           
    
}
pdo_begin();
try {
	foreach ($UpUser as $item) {
		if (isset($item['wallet_pledge_freeze'])) {
			pdo_update('jy_jdpm_member',array('wallet_pledge_freeze -='=>$item['wallet_pledge_freeze']),array('mid'=>$item['mid']));
		}else{
			if ($item['type'] == '-') {
				pdo_update('jy_jdpm_member',array('wallet_pledge -='=>$item['wallet_pledge']),array('mid'=>$item['mid']));
			}else{
				pdo_update('jy_jdpm_member',array('wallet_pledge +='=>$item['wallet_pledge']),array('mid'=>$item['mid']));
				pdo_update('jy_jdpm_member',array('brokerage +='=>$item['wallet_pledge']),array('mid'=>$item['mid']));
			}
		}
	}
	foreach($Log as $lg){
		pdo_insert('jy_jdpm_money_log',$lg);
	}
	if($GoodsUser){
		pdo_update('jy_jdpm_freezelog',array('status'=>1,'rtime'=>TIMESTAMP),array('pid'=>$GoodsUser,'status'=>0));
	}
	foreach ($UpOrder as $value) {
		pdo_update('jy_jdpm_order',array('status'=>$value['status']),array('id'=>$value['id']));
	}
pdo_commit();
} catch (\Exception $e) {
	pdo_rollback();
}